package com.jz.community.modulemine.money.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.callback.LoadingCallback;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.money.bean.MoneyDetailBean;
import com.jz.community.modulemine.money.bean.MoneyInfoBean;
import com.jz.community.modulemine.money.presenter.MoneyDetailPresenter;
import com.jz.community.modulemine.money.ui.adapter.MoneyDetailAdapter;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

@Route(path = RouterIntentConstant.CARD_MONEY_HISTORY)
public class CardMoneyHistoryActivity extends BaseMvpActivity<MoneyDetailView.View, MoneyDetailPresenter> implements MoneyDetailView.View, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R2.id.title_back_left)
    ImageView titleBackLeft;
    @BindView(R2.id.title_name)
    TextView titleName;
    @BindView(R2.id.title_right)
    TextView titleRight;
    @BindView(R2.id.title_right_iv)
    ImageView titleRightIv;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;
    @BindView(R2.id.money_detail_rv)
    RecyclerView moneyDetailRv;
    @BindView(R2.id.money_detail_refresh)
    SmartRefreshLayout moneyDetailRefresh;
    @BindView(R2.id.card_money_layout)
    LinearLayout card_money_layout;
    private LoadService loadService;

    private View loadingView;
    //无数据显示
    private View noDataView;

    private List<MoneyDetailBean.EmbeddedBean.CardPackageLogsBean> money_list = new ArrayList<>();
    private MoneyDetailAdapter adapter_money;

    private int totalPage = 0;
    private int page = 0;
    private int size = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_money_detail;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected MoneyDetailPresenter createPresenter() {
        return new MoneyDetailPresenter(this);
    }

    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventBus(AppEvent message) {
        if (message.tag == EventConfig.REFRESH_MONEY_DETAIL) {
            if (null != adapter_money) {
                adapter_money.replaceData(new ArrayList<>());
            }
            page = 0;
            mPresenter.initMoneyData();
        }

    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(titleToolbar);

        titleName.setText("交易明细");

        EventBus.getDefault().register(this);

        loadService = LoadSir.getDefault().register(card_money_layout, (Callback.OnReloadListener) v -> {
            if (loadService.getCurrentCallback() == ErrorCallback.class) {
                loadService.showCallback(LoadingCallback.class);
                mPresenter.initMoneyData();
            }

        });

        loadService.setCallBack(ErrorCallback.class, (context, view) -> {
            ImageView mIvError = (ImageView) view.findViewById(R.id.error_img);
            mIvError.setImageResource(R.mipmap.error_default);

        });

        loadService.setCallBack(LoadingCallback.class, (context, view) -> {
            ImageView mIvLoading = (ImageView) view.findViewById(R.id.loading_img);
            GlideApp.with(mActivity)
                    .asGif()
                    .load(R.drawable.loading_default)
                    .into(mIvLoading);

        });

        noDataView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) moneyDetailRv.getParent(), false);

        ImageView empty_iv = (ImageView) noDataView.findViewById(R.id.empty_img);
        TextView empty_tv = (TextView) noDataView.findViewById(R.id.empty_tv);

        loadingView = getLayoutInflater().inflate(R.layout.view_loading, (ViewGroup) moneyDetailRv.getParent(), false);

        ImageView loading_iv = (ImageView) loadingView.findViewById(R.id.loading_img);

        GlideApp.with(mActivity)
                .asGif()
                .load(R.drawable.loading_default)
                .into(loading_iv);

        empty_iv.setImageResource(R.mipmap.empty_default);
        empty_tv.setText("暂无交易明细！");
    }

    @Override
    protected void addListener() {
        super.addListener();
        titleBackLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        mPresenter.initMoneyDetailList(page, size);
        initRecyclerView();
    }


    private void initRecyclerView() {
        //主-RecyclerView
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        moneyDetailRefresh.setOnRefreshListener(this);//刷新监听
        moneyDetailRefresh.setEnableLoadMore(false);
        moneyDetailRv.setHasFixedSize(true);
        moneyDetailRv.setFocusable(false);
        moneyDetailRv.setLayoutManager(layoutManager);

        adapter_money = new MoneyDetailAdapter(R.layout.module_mine_item_money, money_list);
        adapter_money.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);//加载动画
        adapter_money.setOnLoadMoreListener(this, moneyDetailRv);
        moneyDetailRv.setAdapter(adapter_money);

    }

    @Override
    public void setMoneyData(MoneyInfoBean entity) {

    }

    @Override
    public void setMoneyDetailData(MoneyDetailBean entity) {
        loadService.showSuccess();
        freshEnd();
        //总页数
        totalPage = entity.getPage().getTotalPages();

        if (totalPage <= 0) {
            //先设置空布局
            if (page == 0) {
                adapter_money.replaceData(new ArrayList<>());
                adapter_money.setEmptyView(noDataView);
                adapter_money.notifyDataSetChanged();
            } else {
                adapter_money.setEmptyView(noDataView);
                adapter_money.notifyDataSetChanged();
            }
        } else {
            money_list = entity.get_embedded().getCardPackageLogs();
            if (page == 0) {
                adapter_money.setNewData(money_list);
                //如果数据少 不显示已加载全部
                adapter_money.disableLoadMoreIfNotFullPage();
            } else {
                adapter_money.addData(money_list);

            }
        }
        adapter_money.loadMoreComplete();

    }

    @Override
    public void showError(String msg) {
        freshEnd();
        loadService.showCallback(ErrorCallback.class);
    }


    private void freshEnd() {
        moneyDetailRefresh.finishRefresh(200);
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        if (null != adapter_money) {
            adapter_money.setEnableLoadMore(false);
            adapter_money.replaceData(new ArrayList<>());
            adapter_money.setEmptyView(loadingView);
        }
        page = 0;
        mPresenter.initMoneyDetailList(page, size);
        adapter_money.setEnableLoadMore(true);

    }

    @Override
    public void onLoadMoreRequested() {
        moneyDetailRefresh.setEnableRefresh(false);
        if (totalPage > 0) {
            if (page < totalPage - 1) {
                page++;
                mPresenter.initMoneyDetailList(page, size);
                moneyDetailRefresh.setEnableRefresh(true);
            } else {
                adapter_money.loadMoreEnd();
                moneyDetailRefresh.setEnableRefresh(true);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
